﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLZJFurnitureSCM.BLL;
using QLZJFurnitureSCM.Model;
using System.Threading;

namespace QLZJFurnitureSCM.WinForm
{
    public partial class FrmSaleRecord : Form
    {
        private OrderService orderService = null;
        private OrderProductService orderProductService = null;
        private List<Order> lstOrder = null;
        private List<OrderProduct> lstOrderProduct = null;
        private List<OrderProduct> lstProductsShow = null;
       // private bool canChangePayStatus = false;
        private List<Order> lstSearch = null;
        private int needProcessOrderCount = 0;
        //private DataGridViewCellMouseEventArgs cellMouseEventArgs = null;

        //private DataSet ds = new DataSet();

        //private DataGridViewColumn[] dgvColArr = null;
        //private DataGridViewColumnCollection dgvColCollection = null;

        public FrmSaleRecord()
        {
            InitializeComponent();
            
        }

        private delegate void DrawDataGridViewDelegate();

        private void DrawDataGridView()
        {
            InitDgvOrders();
            SetDgvHeaderText();
            FindAllOrdersProduct();
        }

        public FrmSaleRecord(ref int count):this()
        {
            this.needProcessOrderCount = count;
            /*
            this.lstOrder = orderUnpay;
            canChangePayStatus = true;
            InitializeComponent();
            InitDgvOrders();
            SetDgvHeaderText();
            FindAllOrdersProduct();*/
            
        }

        private void InitDgvOrders()
        {
            //dataGridViewOrders.Columns.AddRange(dgvColArr);

            orderService = new OrderService();
            if(null == lstOrder)
                lstOrder = orderService.FindAll();

            dataGridViewOrders.DataSource = lstOrder;

            dataGridViewOrders.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            /*
            foreach (Order order in lstOrder)
            {
                dataGridViewOrders.Rows.Add(new object[] { 
                    order.OrderId, 
                    order.OrderNo, 
                    order.OrderContact, 
                    order.OrderTime, 
                    order.OrderDriveEmployee, 
                    order.OrderByUser,
                    order.OrderPayStatus,
                    order.OrderPay});
            }*/

            //dataGridViewOrders.Columns[].Name 
            //colOrderIdIndex = dataGridViewOrders.Columns["dgvColOrderId"].Index;
            //Thread thread = new Thread(new ThreadStart(FindAllOrdersProduct));
            //thread.Start();
            
        }

        private void SetDgvHeaderText()
        {
            
            DataGridViewCellStyle priceCellStyle = new DataGridViewCellStyle();
            priceCellStyle.Format = "C1";
            priceCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            /*
            DataGridViewTextBoxColumn colOrderId = new DataGridViewTextBoxColumn();
            colOrderId.Name = "OrderId";
            colOrderId.Visible = false;
            DataGridViewTextBoxColumn colOrderNo = new DataGridViewTextBoxColumn();
            colOrderNo.Name = "OrderNo";
            colOrderNo.HeaderText = "订单编号";
            DataGridViewTextBoxColumn colOrderContact = new DataGridViewTextBoxColumn();
            colOrderContact.Name = "OrderContact";
            colOrderContact.HeaderText = "客户";
            DataGridViewTextBoxColumn colOrderTime = new DataGridViewTextBoxColumn();
            colOrderTime.Name = "OrderTime";
            colOrderTime.HeaderText = "下单时间";
            DataGridViewTextBoxColumn colOrderDriveEmployee = new DataGridViewTextBoxColumn();
            colOrderDriveEmployee.Name = "OrderDriveEmployee";
            colOrderDriveEmployee.HeaderText = "司机";
            DataGridViewTextBoxColumn colOrderByUser = new DataGridViewTextBoxColumn();
            colOrderByUser.Name = "OrderByUser";
            colOrderByUser.HeaderText = "操作人";

            DataGridViewCheckBoxColumn colOrderPayStatus = new DataGridViewCheckBoxColumn();
            colOrderPayStatus.Name = "OrderPayStatus";
            colOrderPayStatus.HeaderText = "支付";

            DataGridViewTextBoxColumn colOrderPay = new DataGridViewTextBoxColumn();
            colOrderPay.Name = "OrderPay";
            colOrderPay.DefaultCellStyle = priceCellStyle;
            colOrderPay.HeaderText = "金额";

            dgvColArr = new DataGridViewColumn[]
                {
                    colOrderId,
                    colOrderNo,
                    colOrderContact,
                    colOrderTime,
                    colOrderDriveEmployee,
                    colOrderByUser,
                    colOrderPayStatus,
                    colOrderPay
                };*/
            

            //dataGridViewOrders.Columns.AddRange();

            DataGridViewCheckBoxCell dgvChkCell = new DataGridViewCheckBoxCell();

            dataGridViewOrders.Columns["OrderId"].Visible = false;
            dataGridViewOrders.Columns["OrderNo"].HeaderText = "订单号";
            dataGridViewOrders.Columns["OrderContact"].HeaderText = "客户";
            dataGridViewOrders.Columns["OrderTime"].HeaderText = "下单时间";
            dataGridViewOrders.Columns["OrderDriveEmployee"].HeaderText = "司机";
            dataGridViewOrders.Columns["OrderByUser"].HeaderText = "操作员";
            dataGridViewOrders.Columns["OrderPayStatus"].HeaderText = "支付";
            //dataGridViewOrders.Columns["OrderPayStatus"]. = dgvChkCell;
            dataGridViewOrders.Columns["OrderPay"].HeaderText = "金额";
            dataGridViewOrders.Columns["OrderPay"].DefaultCellStyle = priceCellStyle;
            /*
            decimal sum = (from t in lstPurchase select t.PurchaseTotalPrice).Sum();
            string sumChs = ConvertToChinese(sum);
            this.toolStripStatusLabelFrmRecordView.Text = string.Format("历史统计得:进货 {0} 次, 商品 {1} 件, 资金: {2} 元 合: {3}.", lstPurchase.Count, (from t in lstPurchase select t.PurchaseCount).Sum(), sum.ToString("C1"), sumChs);
             */

            //cellMouseEventArgs = new DataGridViewCellMouseEventArgs(1, 1, dataGridViewOrders.Location.X, dataGridViewOrders.Location.Y, new MouseEventArgs(MouseButtons.Left, 1, MousePosition.X, MousePosition.Y, 1));
        }

        private void FindAllOrdersProduct()
        {
            orderProductService = new OrderProductService();
            lstOrderProduct = orderProductService.FindAll();
        }

        private void dataGridViewOrders_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //MessageBox.Show(dataGridViewOrders.Columns[e.ColumnIndex].Name);
            if(e.RowIndex == -1)
                return;
            int index = dataGridViewOrders.Columns["OrderPayStatus"].Index;
            if(e.ColumnIndex == index)
            {
                if (false == Convert.ToBoolean(dataGridViewOrders[index, e.RowIndex].Value))
                {
                    if (DialogResult.Yes == MessageBox.Show("更改此订单状态为已支付?", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                    {
                        //update
                        Order order = new Order();
                        order.OrderId = int.Parse(dataGridViewOrders["OrderId", e.RowIndex].Value.ToString());
                        if (orderService.UpdatePayStatus(order))
                        {
                            this.dataGridViewOrders[index, e.RowIndex].Value = true;
                            this.dataGridViewOrders.UpdateCellValue(e.ColumnIndex, e.RowIndex);
                            //if(canChangePayStatus)
                            //{
                                lstOrder.Remove((from o in lstOrder where o.OrderId == order.OrderId select o).Single());
                            if(needProcessOrderCount > 0)
                                needProcessOrderCount--;
                            //}
                        }
                    }
                }
            }
            dataGridViewProducts.Rows.Clear();
            int orderId = int.Parse(dataGridViewOrders["OrderId", e.RowIndex].Value.ToString());
            lstProductsShow = (from orderProduct in lstOrderProduct where orderProduct.OrderId == orderId select orderProduct).ToList();
            foreach (OrderProduct product in lstProductsShow)
            {
                dataGridViewProducts.Rows.Add(new object[] { product.ProductName, product.Dimension, product.Price, product.BuyCount });
            }
        }

        private void dataGridViewOrders_Paint(object sender, PaintEventArgs e)
        {
            for (int i = 0; i < this.dataGridViewOrders.Rows.Count; )
            {
                this.dataGridViewOrders.Rows[i].DefaultCellStyle.BackColor = SystemColors.ActiveBorder;
                i += 2;
            }
        }

        private void dataGridViewProducts_Paint(object sender, PaintEventArgs e)
        {
            for (int i = 0; i < this.dataGridViewProducts.Rows.Count; i += 2)
                this.dataGridViewProducts.Rows[i].DefaultCellStyle.BackColor = SystemColors.ActiveBorder;
        }

        private void cboSearchType_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*
            所有记录
            订单号
            未支付
            客户
            下单时间
             */
            int selectIndex = cboSearchType.SelectedIndex;
            switch (selectIndex)
            {
                case 0:
                    this.txtKeyword.Enabled = false;
                    this.dateTimePickerSearch.Enabled = false;
                    break;
                case 1:
                    this.txtKeyword.Enabled = true;
                    this.dateTimePickerSearch.Enabled = false;
                    break;
                case 2:
                   this.txtKeyword.Enabled = false;
                    this.dateTimePickerSearch.Enabled = false;
                    break;
                case 3:
                    this.txtKeyword.Enabled = true;
                    this.dateTimePickerSearch.Enabled = false;
                    break;
                case 4:
                    this.txtKeyword.Enabled = false;
                    this.dateTimePickerSearch.Enabled = true;
                    break;
            }

            if (selectIndex == 0 || selectIndex == 2)
                btnSearch_Click(null, null);
            //if(lstOrder.Count > 0)
            //    dataGridViewOrders_CellMouseClick(sender, cellMouseEventArgs);
        }

        

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = string.Empty;
            
            int selectIndex = cboSearchType.SelectedIndex;
            switch (selectIndex)
            {
                case 0:
                    //if (dataGridViewOrders.DataSource != lstOrder)
                        lstSearch = lstOrder;
                    break;
                case 1:
                    keyword = this.txtKeyword.Text;
                    lstSearch = (from o in lstOrder where o.OrderNo.Contains(keyword) select o).ToList();
                    break;
                case 2:
                    lstSearch = (from o in lstOrder where o.OrderPayStatus == false select o).ToList();
                    break;
                case 3:
                    keyword = this.txtKeyword.Text;
                    lstSearch = (from o in lstOrder where o.OrderContact.Contains(keyword) select o).ToList();
                    break;
                case 4:
                    keyword = this.dateTimePickerSearch.Value.ToString("yyyyMMdd");
                    lstSearch = (from o in lstOrder where o.OrderTime.ToString("yyyyMMdd").Equals(keyword) select o).ToList();
                    break;
            }

            //dataGridViewOrders.Columns.Clear();
            //dataGridViewOrders.Columns.AddRange(dgvColArr);
            dataGridViewOrders.DataSource = lstSearch;
        }

        private void FrmSaleRecord_Load(object sender, EventArgs e)
        {
            if(this.cboSearchType.SelectedIndex < 0)
                this.cboSearchType.SelectedIndex = 0;

            this.Invoke(new DrawDataGridViewDelegate(DrawDataGridView));

            if(needProcessOrderCount > 0)
            {
                this.cboSearchType.SelectedIndex = 2;
                btnSearch_Click(null, null);
            }
        }
    }
}
